﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Lon.IO.Ports
{
    class TJWX2000CanHelper
    {

    }
    #region TJWX协议说明

    //ID Bit11:  DIR – 方向位； 0 – 主机到采集机； 1 – 采集机到主机
    //   Bit10:  M/S – 帧性质； 0 – “自主帧”； 1 - “应答帧”；
    //   bit9:     G – 优先级    0 -  高优先级 ； 1 – 低优先级;
    //   bit8-bit3: 采集机号 
    //   bit2-bit0: 通信类型  0x04 自主单帧  0x00 应答单帧  0x03 非结束多帧 0x02 结束多帧

    #endregion
    public class RecMultiFrameDealear
    {
        private int recDevNo;
        public List<CanFrame> tempCache = new List<CanFrame>(64);
        public RecMultiFrameDealear(int devNo)
        {
            this.recDevNo = devNo;
        }

        public virtual bool DealCanFrame(CanFrame frame, out byte[] retBuf, out DateTime firstFrameTime, out byte[] endFrameDate)
        {
            retBuf = null;
            firstFrameTime = DateTime.MinValue;
            endFrameDate = null;
            if (frame == null)
            {
                return false;
            }

            int frameFlag = frame.CanId & 0x07;

            if (frameFlag == 0x2)
            {
                tempCache.Add(frame);
                lock (tempCache)
                {
                    retBuf = GetDataBytes();
                    if (retBuf == null) return false;
                    firstFrameTime = tempCache[0].RecTime;
                    tempCache.Clear();
                    return true;
                }
            }
            else if (frameFlag == 0x3)
            {
                tempCache.Add(frame);
            }
            if (frameFlag == 0x00)
            {
                retBuf = new byte[frame.Buf.Length ];
                Array.Copy(frame.Buf, 0, retBuf, 0, retBuf.Length);
                return true;
            }
            return false;
        }

        private byte[] GetDataBytes()
        {
            for (int i = 0; i < tempCache.Count; i++)
            {
                if (tempCache[i].Buf[0] != (i & 0xff)) return null;
            }
            List<byte> dataList = new List<byte>();
            for (int i = 0; i < tempCache.Count - 1; i++)
            {
                for (int j = 1; j < tempCache[i].Buf.Length; j++)
                {
                    dataList.Add(tempCache[i].Buf[j]);
                }
            }
            for (int i = 3; i < tempCache[tempCache.Count - 1].Buf.Length; i++)
            {
                dataList.Add(tempCache[tempCache.Count - 1].Buf[i]);
            }
            return dataList.ToArray();
        }
    }
}
